package com.jk.lyt.util;


import com.jk.lyt.service.UserService;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.misc.BASE64Encoder;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

@Controller
public class PejeController {
    private UserService userService;


    //生成MD5工具类
    public static String md5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            return Hex.encodeHexString(md.digest(data.getBytes(StandardCharsets.UTF_8)));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
//引入依赖
//     <dependency>
//            <groupId>commons-codec</groupId>
//            <artifactId>commons-codec</artifactId>
//            <version>1.13</version>
//        </dependency>
    @RequestMapping("register")
    @ResponseBody
    public String  register(String  pwd)  {
//md5加密
        String md5HexStr = md5(pwd);
        System.out.println(md5HexStr);
//Base64 加密
        Base64 base64 = new Base64();
        String base64Info = base64.encodeToString(md5HexStr.getBytes());
//        BASE64Encoder encoder = new BASE64Encoder();
//       String password64 = encoder.encode(md5HexStr.getBytes());
//        System.out.println(password64);
        System.out.println(base64Info);
        return  base64Info;
    }





    @RequestMapping("login")
    @ResponseBody
    public String  login(String pwd,String aa ){

//        try {
//
//            MessageDigest md = MessageDigest.getInstance("MD5");
//            md.update(pwd.getBytes("utf-8"));
////			md.update("salt".getBytes("utf-8"));				// 往用户密码中添加其他信息，也被称作“加盐”
//            byte[] result = md.digest();
//            System.out.println(result);// 计算散列值
//            String pwds = Base64.encodeBase64String(result); 	// 转为字符串
//            System.out.println(pwds);
//            if(aa.equals(pwds)) {
//                return "成功";
//            }else{
//                return "失败";}
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            return  null;
//        }

        String md5HexStr = md5(pwd);
        System.out.println(md5HexStr);
        Base64 base64 = new Base64();
        String base64Info = base64.encodeToString(md5HexStr.getBytes());
        if(aa.equals(base64Info)) {
                return "成功";
            }else{
               return "失败";}
    }

}
